package com.efounder.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;

import com.core.xml.StubObject;
import com.efounder.broadcast.BroadCastutil;
import com.efounder.constant.Constant;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.ospmobilelib.R;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.MyStaticWebView;
import com.efounder.util.SnapShot;
import com.efounder.util.StorageUtil;
import com.efounder.widget.ESPWebView;
import com.pansoft.appcontext.AppConstant;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

/**
 * 此类用于加载web表单
 * @author Xinqing
 *
 */
public class WebFragmentForGwtForms extends BaseFragment {

	private static final String TAG = "SimpleWebFragment";
	private StubObject mMenuItem;
	private String titleStr;
	private View rootView;// 缓存Fragment view
	private FrameLayout fl;
	private String forms;
	private ESPWebView wv;
	private ImageView imageView;
	private StorageUtil storageUtil;
	 public WebFragmentForGwtForms(){
			super();
		}
	public WebFragmentForGwtForms(StubObject menuItem, String title) {
		this.mMenuItem = menuItem;
		this.titleStr = title;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.normalwebview_forms, container, false);

		Log.i(TAG, "test-----====================SimpleWebFragmentNoRefresh: onCreateView："+"--"+titleStr);
		

		if(null!=savedInstanceState){
			mMenuItem = (StubObject) savedInstanceState.getSerializable("databack");
			titleStr = (String) savedInstanceState.getSerializable("title");
		}
		
		Hashtable menuTable = mMenuItem.getStubTable();
		forms = (String) menuTable.get("forms");
		registerBoradcastReceiver();

		fl = (FrameLayout) rootView.findViewById(R.id.root);
		if (null != forms) {
			LoadingDataUtilBlack.show(WebFragmentForGwtForms.this.getActivity(),"正在请求服务");

			imageView = (ImageView) rootView.findViewById(R.id.snapshot);
			//测试：不显示快照
			//imageView.setVisibility(View.GONE);

			Bitmap bm = null;
			String menuIcon = AppConstant.APP_ROOT+"/res/unzip_res" + "/kuaizhao/" + forms
					+ ".png";
			System.out.println("xxxxxx" + menuIcon);
			File file = new File(menuIcon);
			if (file.exists()) {
				bm = BitmapFactory.decodeFile(menuIcon);
				imageView.setImageBitmap(bm);
			} 

			/*
			 * 1.初始化时，如果webview没有父类，将webview添加到frameLayout中
			 * 2.PagerSlidingTabFragment onHiddenChanged方法中， hidden = true 时，将webView从framelayout中删除 
			 */
			
			/*storageUtil = new StorageUtil(getActivity().getApplicationContext(), "storage");
			if (storageUtil.getBoolean("initweb", false)) {
				Log.i("TimeCheck", "执行了if方法");
				wv = MyStaticWebView.getWv();
			}else {
				Log.i("TimeCheck", "执行了else方法");
				
				
			}*/
			
		} 

		//Window级别 开启硬件加速  注意：现阶段你不能在Window级别对它禁用硬件加速。
		getActivity().getWindow().setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
		
		super.onCreateView(inflater, container, savedInstanceState);
		return rootView;

	}
	


	@Override
	public void onDestroy() {
		super.onDestroy();
		// BroadCastutil.getinstance().unregisterWebBroadcastList((Context)SimpleWebFragmentNoRefresh.this.getActivity());
	}

	

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(forms)) {
				String type = intent.getStringExtra("type");
				if (("dataLoaded").equals(type)) {// js 发送dataLoaded调用
					Log.i(TAG, "3 webView---------------显示webView：mBroadcastReceiver:"+titleStr);
					showWebView(300); 
					LoadingDataUtilBlack.dismiss();
					//快照
					saveSnapShot(500);
				}

			}

		}

	};

	/**
	 * 保存快照
	 */
	public void saveSnapShot(long delayMillis){
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				//快照
				SnapShot snapShot = new SnapShot();
				String fromtilte = forms + ".png";
				String dir = AppConstant.APP_ROOT+"/res/unzip_res"
						+ "/kuaizhao";
				Bitmap bitmap = snapShot.shot(wv, dir, fromtilte);
				imageView.setImageBitmap(bitmap);
			}
		}, delayMillis);
	}
	
	public void registerBoradcastReceiver() {
		boolean a = (null != forms);
		System.out.println(a);
		if (!a)
			return;
		boolean b = (!("").equals(forms));
		System.out.println(b);
		if (null != forms || !("").equals(forms)) {
			IntentFilter myIntentFilter = new IntentFilter();
			myIntentFilter.addAction(forms);
			// 注册广播
			this.getActivity().registerReceiver(mBroadcastReceiver,
					myIntentFilter);
			BroadCastutil.getinstance().addbroadCast(mBroadcastReceiver);
		}
	}

	/**
	 * webView加载数据
	 * @return
	 */
	public ESPWebView webViewLoadForm() {
		LoadingDataUtilBlack.show(WebFragmentForGwtForms.this.getActivity(),"正在请求服务");
		MyStaticWebView.setFormtitle(forms);
		
		 Thread t = new Thread(new Runnable(){  
	            public void run(){  
	            
	         
			
		//ESPWebView wv = MyStaticWebView.getWv();
		boolean isinitover =wv.isIsinitover();
        while(!isinitover){
        	try {
        	       Thread.sleep(100);                           
        	     } catch (InterruptedException e) {
        	} 
        	isinitover = wv.isIsinitover();
		}

		String contentView = (String) mMenuItem.getStubTable().get(
				"contentView");
		String jsonFilePath = AppConstant.APP_ROOT+"/res/unzip_res"
				+ "/Form/" + forms +".json";
		File jsonFile = new File(jsonFilePath); 
		if (jsonFile.exists()) {
			String json = getJsonFromFile(jsonFilePath);
			String url = "javascript:loadFormWithJSONByIOS('"+forms+"', '"+contentView+"', \""+json+"\")";
			wv.loadUrl(url);
		}else {
			String url = "javascript:function myFunction(){var nodeObject = new Object(); nodeObject[\"forms\"] = '"
					+ forms
					+ "'; nodeObject[\"contentView\"] = '"
					+ contentView + "'; window.openForm(nodeObject);}";
			wv.loadUrl(url);
			wv.loadUrl("javascript:myFunction()");
		}
		
		Log.i("test-form-time", "-----------> startLoadForm:" + new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()) 
				+ "----表单：" + titleStr + "("+forms+")----是否从本地调用：" + jsonFile.exists() +"-----是否开启硬件加速：" + wv.isHardwareAccelerated());
		Constant.currentTimeMillis = System.currentTimeMillis();
	            }});  
	        t.start();  
		return wv;	}
	
	/**
	 * 
	 * 从文件中读取json字符串
	 * @param filePath
	 * @return
	 */
	private String getJsonFromFile(String filePath){
		long currentTime = System.currentTimeMillis();
		String json = null;
		FileInputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader bufferedReader = null;
		try {
			inputStream = new FileInputStream(filePath);
			inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			bufferedReader = new BufferedReader(inputStreamReader);
			
			StringBuffer stringBuffer = new StringBuffer();
			String tempString = null;
			while ((tempString = bufferedReader.readLine()) != null) {
				stringBuffer = stringBuffer.append(tempString);
			}
			json = string2Json(stringBuffer.toString());

			Log.i(TAG, "android-alert------json字符串长度："+json.length()+"------生成json所用时间：" + (System.currentTimeMillis() - currentTime));
		} catch (FileNotFoundException e) { 
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
				if (inputStreamReader != null) {
					inputStreamReader.close();
				}
				if (inputStream != null){
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return json;
	}
	
	/**
	 *  JSon 数据中的String 传递数据时，需要处理好特殊字符 
		JSon数据中有特殊字符 
		1 :引号   如果是使用单引号，来括值的话，那String 中  '  单引号为特殊字符 
		2：正斜杠，反斜杠，换行符号等 。
		另外，必须用 (") 而非 (') 表示字符串： 
	 * @param s
	 * @return
	 */ 
	private String string2Json(String s) {     
	    StringBuffer sb = new StringBuffer ();     
	    for (int i=0; i<s.length(); i++) {     
	   
	        char c = s.charAt(i);     
	        switch (c) {     
	        case '\"':     
	            sb.append("\\\"");     
	            break;     
	        case '\\':     
	            sb.append("\\\\");     
	            break;     
	        case '/':     
	            sb.append("\\/");     
	            break;     
	        case '\b':     
	            sb.append("\\b");     
	            break;     
	        case '\f':     
	            sb.append("\\f");     
	            break;     
	        case '\n':     
	            sb.append("\\n");     
	            break;     
	        case '\r':     
	            sb.append("\\r");     
	            break;     
	        case '\t':     
	            sb.append("\\t");     
	            break;     
	        case '\u2028':     
	        	sb.append("\\u2028");     
	        	break;     
	        case '\u2029':     
	        	sb.append("\\u2029");     
	        	break;     
	        default:     
	            sb.append(c);  
	        }
        }
	    return sb.toString();     
	 }  

	
	/**
	 * 添加webview
	 * @param layout
	 * @return
	 */
	public ESPWebView addWebView(ViewGroup layout){
		removeWebView();
		wv.setLayoutParams(new ViewGroup.LayoutParams(
				LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		if(wv.getParent()!=null)((ViewGroup)wv.getParent()).removeView(wv);
		layout.addView(wv);
		hideWebView();
		return wv;
	}
	
	/**
	 * 移除webview
	 * @return
	 */
	public ESPWebView removeWebView(){
//		if (wv.getParent() != null){
//		Log.i(TAG, "4 webView---------------移除webView： onInvisible:"+titleStr);
//			((ViewGroup) wv.getParent()).removeView(wv);
//		}
		if (wv!=null&&wv.getParent() == fl) {
			Log.i(TAG, "4 webView---------------移除webView： onInvisible:"+titleStr);
			fl.removeView(wv);
		}
		return wv;
	}
	
	/**
	 * 显示webview
	 * @return
	 */
	public ESPWebView showWebView(long delayMillis) {
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				
				int beforejs = wv.getContentHeight();
				System.out.println(beforejs+"..........");
			/*	String url = "javascript:function myFunction1(){" +
						
						" //div.style.height=height;"+
						"document.getElementById(\"gwt_esp\").style.height=\"900px\";" +
						" alert(document.getElementById(\"gwt_esp\").style.height);;}";*/
				String url = "javascript:function myFunction1(){" +
						"var width1 = window.innerWidth;"+
						"var div = document.getElementById(\"bodycontainer\");" +
						"var height1=document.body.scrollHeight; alert(height1);" +
						//"var height1 = window.style.height; alert('height1=='+height1); alert('width1===='+width1);"+
						//"document.getElementById(\"gwt_esp\").style.height=\"667px\";" +
						//" alert(document.getElementById(\"gwt_esp\").style.width);alert(document.getElementById(\"gwt_esp\").style.height);" +
						//" window.setViewportSize(667,1000);" +
						" window.scrollTo(0, 0);  var size = 1.0;    document.body.style.cssText = document.body.style.cssText + '; -webkit-transform: scale('+size+'); -webkit-transform-origin: 0 0;';  alert('bodycsstext = '+document.body.style.cssText);  zoom1();  "+
						//"document.write('<meta name=\"viewport\" content=\"initial-scale=0.5\">')"+
						//" document.getElementById(\"viewport\").setAttribute(\"content\",\"initial-scale=0.5, maximum-scale=1.0, user-scalable=0\"); " +
						"}";
				System.out.println(url);
				//wv.setInitialScale(100);
				System.out.println("scale==========="+wv.getScale()/3);
				System.out.println("scale==========="+100/(wv.getScale()/3));
				
				wv.loadUrl(url);
				wv.loadUrl("javascript:myFunction1()");

				while(wv.canZoomOut())
				wv.zoomOut();

				//wv.setScaleX((float) 0.5);
				//wv.setScaleY((float) 0.5);
				//wv.setScaleX((float) 0.5);
			//	wv.getSettings().setSupportZoom(false);
				//wv.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
				MyStaticWebView.setScaleVsalue(wv, 50);
				int afterjs = wv.getContentHeight();
				//FIXME 显示动画
				AlphaAnimation mShowAnimation = new AlphaAnimation(0.0f, 1.0f);
				mShowAnimation.setDuration(300);
//				wv.startAnimation(mShowAnimation);
				wv.setVisibility(View.VISIBLE);
			}
		}, delayMillis);
		

		return wv;
	}
	
	/**
	 * 
	 * 隐藏webview
	 * @return
	 */
	public ESPWebView hideWebView(){
		wv.setVisibility(View.INVISIBLE);
		return wv;
	}
	
	@Override
	public void onVisible() {
		Log.i(TAG, "test-----====================SimpleWebFragmentNoRefresh: onVisible："+"--"+titleStr);
		//1 加载数据
		Log.i(TAG, "1 webView---------------加载数据：onVisible:"+titleStr);
		wv = MyStaticWebView.getWv();
		webViewLoadForm();
		Log.i(TAG, "2 webView---------------添加webView：隐藏：onVisible:"+titleStr);
		addWebView(fl);
		super.onVisible();
	}
	
	@Override
	public void onInvisible() {
		Log.i(TAG, "test-----====================SimpleWebFragmentNoRefresh: onInvisible："+"--"+titleStr);
		// 删除webview
		removeWebView();
		super.onInvisible();
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putSerializable("databack",mMenuItem);
		outState.putSerializable("title",titleStr);
	}
	 
}
